<?php
	require("includes/database.php");

	
	$user = addslashes($_POST[username]);
	$pass = $_POST[password];
	$idSucursal = $_REQUEST['sucursal'];
	
	$sql = "SELECT u.idUsuario, u.apellido, u.nombre, s.idSucursal, s.nombre as sucursal FROM usuarios u join sucursalesxusuario sxu on u.idUsuario = sxu.idUsuario join sucursales s on sxu.idSucursal = s.idSucursal WHERE username='" . $user . "' AND password='" . md5($pass) . "' AND s.idSucursal = $idSucursal";
	
	echo $sql;
	exit;
	$result = readSQL($sql);
	
	$fecha = getdate();
	$mes = $fecha[mon];
	$ano = $fecha[year];
	
	if($mes == 1)
	{
		$mes = 12;
		$ano--;
	}
	else
	{
		$mes--;
	}

	if(count($result) == 0)
	{
		$sql = "SELECT idUsuario from usuarios WHERE username='" . $user . "'";
		$result = readSQL($sql);
		if(count($result) == 0)
			header("Location: index.php?error=0");
		else
			header("Location: index.php?error=1&user=" . $user);
	}
	else
		{
			session_start();
			foreach($result as $value)
			{
				$_SESSION['username'] = $_POST[username];
				$_SESSION['idUsuario'] = $value['idUsuario'];
				$_SESSION['nombre'] = $value['nombre'];
				$_SESSION['apellido'] = $value['apellido'];
				$_SESSION['idSucursal'] = $value['idSucursal'];
				$_SESSION['sucursal'] = $value['sucursal'];
				
				/*
				$sql = "select round((select count(idorden) from ordenes where idusuario = ".$_SESSION['idUsuario']." and fechahorafin between '$ano-$mes-01' and '$ano-$mes-31' and idestado in (select idestado from estados where nombre like '%reparado%'))/
(select count(idorden) from ordenes where idusuario = ".$_SESSION['idUsuario']." and fechahorafin between '$ano-$mes-01' and '$ano-$mes-31')*100) as reparabilidad";

				$resultReparabilidad = readSQL($sql);
				foreach($resultReparabilidad as $valueReparabilidad)
				{
					$_SESSION['reparabilidad'] = $valueReparabilidad['reparabilidad'];
				}
				*/
				
				$arr = array();
				$sql2 = "SELECT p.idPermiso FROM usuariosxperfil u JOIN permisosxperfil p ON (u.idPerfil = p.idPerfil) WHERE u.idUsuario=" . $value['idUsuario'];
				
				$result2 = readSQL($sql2);
				if(count($result2) != 0)
				{
					foreach($result2 as $value2)
					{
						array_push($arr, $value2['idPermiso']);
					}
					$_SESSION['permisos'] = $arr;
					
					header("Location: main.php");
				}
				else
					header("Location: index.php?error=2");
			}
		}
?>